<template>
  <table :style="{'width':w+'px'}">
    <thead>
      <tr>
        <th><input type="checkbox" name="" id="" @click="allCk" /></th>
        <th>序号</th>
        <th>书籍名称</th>
        <th>出版日期</th>
        <th>价格</th>
        <th>购买数据</th>
        <th>操作</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="(item, index) in books">
        <td>
          <input
            type="checkbox"
            name=""
            id=""
            @click="ck(index)"
            :checked="item.flag"
          />
        </td>
        <td>{{ index + 1 }}</td>
        <td>{{ item.name }}</td>
        <td>{{ item.time }}</td>
        <td>￥{{ item.price }}</td>
        <td>
          <button @click="sub(index)">-</button> <span>{{ item.num }}</span>
          <button @click="add(index)">+</button>
        </td>
        <td><button @click="goMove(index)">移出</button></td>
      </tr>
    </tbody>
  </table>
  <button @click="checkRemove">删除所选</button>
  <h3>总价：￥{{ allPrice }}</h3>
</template>

<script setup lang="ts">
import { reactive,computed } from "vue";
import {useResize} from "./../../hooks/useResize"; 
let {w}=useResize();
console.log(w);
let books = reactive([
  {
    name: "《算法导论》",
    time: "2012-9",
    price: "89.00",
    num: 1,
    flag: false,
  },
  {
    name: "《大数据》",
    time: "2012-9",
    price: "79.00",
    num: 1,
    flag: false,
  },
  {
    name: "《高级程序设计》",
    time: "2012-9",
    price: "67.00",
    num: 1,
    flag: false,
  },
  {
    name: "《成语大全》",
    time: "2012-9",
    price: "99.00",
    num: 1,
    flag: false,
  },
]);

// 增加
let add = (index) => {
  books[index].num++;
};
// 减少
let sub = (index) => {
  if (books[index].num <= 1) {
    alert("数量不能小于1！");
  } else {
    books[index].num--;
  }
};
// 删除
let goMove = (index) => {
  books.splice(index, 1);
  // 插入：arr.push()和arr.unshift()
  // 删除：arr.pop()和arr.shift()
  // 删除、插入、替换：splice()
};
// 选中
let ck = (index) => {
  books[index].flag = !books[index].flag;
  console.log(books);
};
// 全选
let allCk = () => {
  books.forEach(function (item) {
    item.flag = !item.flag;
  });
};
// 删除所选
let checkRemove = () => {
  for (let i = 0; i < books.length; i++) {
    if (books[i].flag) {
      books.splice(i, 1);
      i--;
    }
  }
};

// 计算属性
let allPrice = computed(() => {
  let all = 0;
  books.forEach((item) => {
    all += item.price as unknown as number * item.num;
  });
  return all;
});
</script>

<style scoped></style>
